#!/usr/bin/env python
# -*- coding:utf-8 -*-

import json
import uuid

import handlers.base as baseHandler
import methods.chatMessage as chatMessage

unique_id = lambda: str(uuid.uuid1())
json_encoder = json.JSONEncoder()
json_encode = json_encoder.encode


class ChatPageController(baseHandler.BaseHandler):
    def get(self):
        self.render("templates/message.html")

class ChatMessageHandler(baseHandler.BaseHandler):
    chatm=chatMessage.Chat();
    @baseHandler.asynchronous
    def get(self):
        roomId=self.get_argument("roomId").strip()
        callbacks={roomId:self.on_message}
        self.chatm.register(callbacks)

    def on_message(self, message):
        if(self.get_cookie("xxgame_roomId")==message[0]['roomId']):
            rstMsg=str(message[0]['username'])+":"+str(message[0]['content'])
            update_msg = json_encode({"id":1, "msg":rstMsg})
            self.finish(update_msg)

    def post(self):
        roomId = self.get_argument("roomId").strip()
        username = self.get_argument("username").strip()
        content = self.get_argument("content").strip()
        param={"roomId":roomId,"username":username,"content":content}
        self.chatm.add_message(param)